package core.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.ibatis.session.ResultContext;

/**
 * @author songduk park
 * 
 */
public class CSVResultHandler implements AbstractResultHandler {

	protected File file;
	protected BufferedWriter out;

	protected String[] headers;
	protected String[] columns;

	public CSVResultHandler(File file, String[] headers, String[] columns) {
		this.file = file;
		this.headers = headers;
		this.columns = columns;

		try {
			out = new BufferedWriter(new FileWriter(file), 4096);

			// print head
			for (String header : headers) {
				String value = changeToCSV(header);
				out.write(value + ",");
			}
			out.write("\n");

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void handleResult(ResultContext context) {
		StringHashMap row = (StringHashMap) context.getResultObject();

		// print 1 line
		try {
			for (String column : columns) {
				Object obj = row.get(column);
				out.write(changeToCSV(obj) + ",");
			}
			out.write("\n");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void printValue(Object obj) {
		try {
			out.write(changeToCSV(obj) + ",");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void printLn() {
		try {
			out.write("\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String changeToCSV(Object cell) {
		if (cell == null) {
			return "\"\"";
		}

		String newCell = cell.toString().replaceAll("\"", "\"\"");
		return "\"" + newCell + "\"";
	}

	@Override
	public void doSomethingAfter() {
		try {
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void doSomethingBefore() {
	}

	public void makeEmpty() {
		doSomethingBefore();
		doSomethingAfter();
	}

}
